package com.esender.smsgateway.runnable;

import com.esender.common.constant.RabbitMQConstants;
import com.esender.common.constant.SmsConstant;
import com.esender.common.enums.CMPP2ResultEnums;
import com.esender.common.model.StandardReport;
import com.esender.common.model.StandardSubmit;
import com.esender.common.util.CMPPDeliverRepoMapUtil;
import com.esender.common.util.CMPPSubmitRepoMapUtil;
import com.esender.common.util.SpringUtil;
import com.esender.smsgateway.client.BeaconCacheClient;
import com.esender.smsgateway.netty4.entity.CmppSubmitResp;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;

public class SubmitRepoRunnable implements Runnable {
    private RabbitTemplate rabbitTemplate = SpringUtil.getBeanByClass(RabbitTemplate.class);
    private CmppSubmitResp cmppSubmitResp;

    public SubmitRepoRunnable(CmppSubmitResp cmppSubmitResp) {
        this.cmppSubmitResp = cmppSubmitResp;
    }

    @Override
    public void run() {
        StandardReport standardReport;
        // 1、拿到自增ID，并且从ConcurrentHashMap中获取到存储的submit
        // 2、根据运营商返回的result，确认短信状态并且封装submit，填充短信状态以及错误信息
        StandardSubmit standardSubmit = CMPPSubmitRepoMapUtil.get(cmppSubmitResp.getSequenceId());

        int result = cmppSubmitResp.getResult();
        if (result != 0) {
            CMPP2ResultEnums cmpp2ResultEnums = CMPP2ResultEnums.getResultMsg(result);
            standardSubmit.setReportState(SmsConstant.REPORT_FAIL);
            standardSubmit.setErrorMsg(cmpp2ResultEnums.getMsg());
        } else {
            // 如果没有进到if中，说明运营商已经正常的接收了发送短信的任务，这边完成3操作
            // 3、将submit封装为Report，临时存储，以便运营商返回状态码时，可以再次获取到信息。
            standardReport = new StandardReport();
            BeanUtils.copyProperties(standardSubmit, standardReport);

            CMPPDeliverRepoMapUtil.put(cmppSubmitResp.getMsgId() + "",standardReport);
        }
        // 4、将封装好的submit直接仍在rabbitmq中，让搜索模块记录信息
        rabbitTemplate.convertAndSend(RabbitMQConstants.SMS_WRITE_LOG,standardSubmit);
    }

}
